package de.hijacksoft.isledesktopsync.adapter;

import de.hijacksoft.isledesktopsync.SettingsManager;
import static de.hijacksoft.isledesktopsync.Globals.*;
import java.util.ArrayList;
import java.util.Scanner;

public class ADBAdapter {

    public static final String FORWARD = "forward tcp:$p0 tcp:$p0";

    public static final int WINDOWS = 0;
    public static final int LINUX = 1;
    public static final int MACOS = 2;
    
    /**
     * Runs the android debug bridge command of forwarding the ports
     * @param command The command to be executed with the adb
     * @param parameter Optional parameters to the command. Set this to null if the command has no parameter
     */
    public static void exec(String command, String ... parameter) {
        
        // build command
        if(parameter != null)
            for(int i = 0; i < parameter.length; i++){
                command = command.replaceAll("\\$p" + i, parameter[i]);
            }
        try {
        
            Runtime runtime = Runtime.getRuntime();
            Process p;
            
            // get the path to the android sdk
            String adbPath = SettingsManager.getInstance().getString(SETTING_ADBPATH);
            
            // select the platform
            String osName = System.getProperty("os.name");
            int platform = LINUX;
            if(osName.contains("Mac OS")) platform = MACOS;
            if(osName.contains("Windows")) platform = WINDOWS;
            if(platform != WINDOWS && platform != LINUX && platform != MACOS) platform = WINDOWS;
            
            // execute
            switch(platform){
                case WINDOWS: p = runtime.exec(adbPath + "\\platform-tools\\adb.exe " + command); break;
                case LINUX  : p = runtime.exec(adbPath + "/platform-tools/adb " + command); break; 
                case MACOS  : p = runtime.exec(adbPath + "/platform-tools/adb " + command); break;
                default : p = runtime.exec(adbPath + "/platform-tools/adb.exe " + command); break;
            }
            
            // System.out.println("ADBAdapter: executing " + command);
            
            // fetch errors
            Scanner sc = new Scanner(p.getErrorStream());            
            if (sc.hasNext()) {
                // System.err.print("ADBAdapter: ");
                while (sc.hasNext()) {
                    // System.err.print(sc.next() + " ");
                }
                // System.err.print("\n");
            }

        } catch (Exception e) {
            // System.err.println("ADBAdapter:" + e.toString());
        }
    }

}
